/*
 * Copyright (C) 2015 Bilibili
 * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.living.player.ui.player;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.living.Constant;
import com.living.R;
import com.living.filedownloader.DownLoadManger;
import com.living.filedownloader.ui.TasksDownloadedActivity;
import com.living.player.LivePlayerView;
import com.living.player.db.AudioPlayListManger;
import com.living.player.db.RecentlyManger;
import com.living.player.dialog.RecentPlayListDialog;
import com.living.player.event.EventMediaChange;
import com.living.player.event.EventPlayNewData;
import com.living.player.event.EventStatusPause;
import com.living.player.event.EventStatusPlay;
import com.living.player.services.MediaPlayerServiceImp;
import com.living.player.widget.media.OnPauseResumeListener;
import com.living.widget.LockableNestedScrollView;
import com.md.basedpc.PHBarUtils;
import com.md.basedpc.PHSizeUtils;
import com.md.basedpc.autosize.AutoSize;
import com.md.basedpc.base.BaseActivity;
import com.md.basedpc.persistence.PHSPUtil;
import com.md.livingwidget.indicator.SmartTabLayout;
import com.md.livingwidget.toast.PHToast;
import com.md.livingwidget.uiutils.SvgUtil;
import com.md.network.api.Album;
import com.md.network.api.Audio;
import com.yxt.function_sdk_share.constants.SHARE_TYPE;
import com.yxt.function_sdk_share.util.ShareUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

public class VideoActivity extends BaseActivity implements View.OnClickListener { // implements TracksFragment.ITrackHolder {
    private static final String TAG = "VideoActivity";
    private View root_video;
    private LockableNestedScrollView video_lockablenestedscrollview;
    private float startY;
    private float moveY = 0;
    private boolean isActionMove = false, isStartDrag = false;
    private int nestedScrollY = 0;
    private int startScrollY = 0;
    private ImageView iv_play_download;
    private ViewPager videoViewPager;
    private SmartTabLayout smartTab;
    private String mVideoPath;
    private LivePlayerView mPlayer;
    private ImageView orderButton;

    private Audio audio;
    private List<Fragment> fragmentList = new ArrayList();
    private PlayingFragment playingFragment;
    private PlayInfoFragment playInfoFragment;
    private RecentPlayListDialog recentPlayListDialog;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        startScrollY = PHSizeUtils.mm2px(this, 150);
        setContentView(R.layout.activity_player_main);
        iv_play_download = findViewById(R.id.iv_play_download);
        mPlayer = findViewById(R.id.player);
        root_video = findViewById(R.id.root_video);
        LinearLayout layout_player_top_bar = findViewById(R.id.layout_player_top_bar);
        video_lockablenestedscrollview = findViewById(R.id.video_lockablenestedscrollview);
        videoViewPager = findViewById(R.id.videoViewPager);
        smartTab = findViewById(R.id.smartTab);

        PHBarUtils.setStatusBarColor(this, getResources().getColor(R.color.transparent));
        PHBarUtils.subtractMarginTopEqualStatusBarHeight(root_video);
        layout_player_top_bar.setPadding(0, PHBarUtils.getStatusBarHeight(), 0, 0);

        iv_play_download.setOnClickListener(this);
        findViewById(R.id.iv_play_backstack).setOnClickListener(this);
        findViewById(R.id.iv_play_share).setOnClickListener(this);

        video_lockablenestedscrollview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//                Log.e("onScrollChange:" + "scrollY:" + scrollY + "====oldScrollY:" + oldScrollY);
                nestedScrollY = scrollY;
            }
        });
        recentPlayListDialog = new RecentPlayListDialog(this);
        mPlayer.getMenuButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recentPlayListDialog.showDialog();
            }
        });
        orderButton = mPlayer.getOrderButton();
        refreshOrder();
        orderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int order = PHSPUtil.getInstance().getInt(Constant.player_order, 0);
                if (order == 0) {
                    // 顺序播放
                    PHSPUtil.getInstance().putInt(Constant.player_order, 1);
                } else if (order == 1) {
                    // 单曲循环
                    PHSPUtil.getInstance().putInt(Constant.player_order, 2);
                } else {
                    // 随机播放
                    PHSPUtil.getInstance().putInt(Constant.player_order, 0);
                }
                refreshOrder();
            }
        });
        mPlayer.setPrevNextListeners(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Audio audio = MediaPlayerServiceImp.getNextAudio();
                if (audio != null) {
                    MediaPlayerServiceImp.playAudio(getmContext(), audio);
                } else {
                    Toast.makeText(getmContext(), "没有下一曲", Toast.LENGTH_LONG).show();
                }
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Audio audio = MediaPlayerServiceImp.getLastAudio();
                if (audio != null) {
                    MediaPlayerServiceImp.playAudio(getmContext(), audio);
                } else {
                    Toast.makeText(getmContext(), "没有上一曲", Toast.LENGTH_LONG).show();
                }
            }
        });
        mPlayer.setOnPauseResumeListener(new OnPauseResumeListener() {
            @Override
            public boolean isCanPauseResume() {
                if (MediaPlayerServiceImp.getMediaPlayer() == null) {
                    if (MediaPlayerServiceImp.getCurrentPlayAudio() != null) {
                        MediaPlayerServiceImp.playAudio(getmContext(), MediaPlayerServiceImp.getCurrentPlayAudio());
                    }
                    return false;
                }
                return true;
            }
        });
        initData();
    }

    public void initData() {
        Intent intent = getIntent();
        if (intent.hasExtra("audio")) {
            audio = (Audio) intent.getParcelableExtra("audio");
            mVideoPath = audio.getAudioUrl();
            mPlayer.playMadia(mVideoPath);
            MediaPlayerServiceImp.setCurrentPlayAudio(audio);
            EventBus.getDefault().post(new EventPlayNewData(audio));
        } else {
            audio = MediaPlayerServiceImp.getCurrentPlayAudio();
            if (audio != null) {
                intent.putExtra("audio", audio);
                mVideoPath = audio.getAudioUrl();
                mPlayer.mVideoView.attachPlay();
            }
        }
        if (audio == null) {
            return;
        }
        playingFragment = new PlayingFragment();
        playInfoFragment = new PlayInfoFragment();
        fragmentList.add(playingFragment);
        fragmentList.add(playInfoFragment);
        VideoAdapter videoAdapter = new VideoAdapter(getSupportFragmentManager(), fragmentList);
        videoViewPager.setAdapter(videoAdapter);
        smartTab.setViewPager(videoViewPager);

        if (!DownLoadManger.getInstance().isAudioExite(audio.getAlbumId(), audio.getId())) {
            iv_play_download.setImageResource(R.drawable.icon_player_download);
            iv_play_download.setClickable(true);
        } else {
            iv_play_download.setImageResource(R.drawable.icon_player_downloaded);
            iv_play_download.setClickable(false);
        }
    }

    @Override
    public void onClick(View view) {
        int _id = view.getId();
        if (_id == R.id.iv_play_download) {
            Album album = new Album(
                    new ArrayList<>(),
                    audio.getAlbumAuthor(),
                    audio.getCoverUrl(),
                    audio.getDesc(),
                    audio.getAlbumId(),
                    0,
                    audio.getAlbumName(),
                    null
            );
            ArrayList<Audio> audioArrayList = new ArrayList<>();
            audioArrayList.add(audio);
            DownLoadManger.getInstance().downloadAudioList(album, audioArrayList);
            iv_play_download.setImageResource(R.drawable.icon_player_downloaded);
            iv_play_download.setClickable(false);
            PHToast.shotBigToast(getmContext(), "已下载");
        } else if (_id == R.id.iv_play_backstack) {
            finish();
        }
    }

    void refreshData() {
        Intent intent = getIntent();
        audio = MediaPlayerServiceImp.getCurrentPlayAudio();
        if (audio != null) {
            intent.putExtra("audio", audio);
            mVideoPath = audio.getAudioUrl();
            playingFragment.initData();
            playInfoFragment.initData();
            recentPlayListDialog.refresh();
        }
        if (!DownLoadManger.getInstance().isAudioExite(audio.getAlbumId(), audio.getId())) {
            iv_play_download.setImageResource(R.drawable.icon_player_download);
            iv_play_download.setClickable(true);
        } else {
            iv_play_download.setImageResource(R.drawable.icon_player_downloaded);
            iv_play_download.setClickable(false);
        }
    }

    private void refreshOrder() {
        int order = PHSPUtil.getInstance().getInt(Constant.player_order, 0);
        if (order == 0) {
            // 顺序播放
            orderButton.setImageDrawable(SvgUtil.convertSvg2SkinDrawable(this, R.drawable.icon_play_control_order_all, Color.parseColor("#bfbfbf")));
        } else if (order == 1) {
            // 单曲循环
            orderButton.setImageDrawable(SvgUtil.convertSvg2SkinDrawable2(this, R.drawable.icon_play_control_order_loop, Color.parseColor("#bfbfbf")));
        } else {
            // 随机播放
            orderButton.setImageDrawable(SvgUtil.convertSvg2SkinDrawable(this, R.drawable.icon_play_control_order_radom, Color.parseColor("#bfbfbf")));
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayer.enterBackground();
    }

    @Subscribe
    public void onEvent(Object event) {
        if (event instanceof EventMediaChange) {
            mPlayer.mVideoView.refreshMedia();
            refreshData();
        } else if (event instanceof EventStatusPlay) {
            if (mPlayer != null) {
                mPlayer.getCostomMediaController().updatePausePlay();
            }
//            player.mVideoView.start();
//            player.mVideoView.attachPlay();
        } else if (event instanceof EventStatusPause) {
//            player.mVideoView.pause();
            if (mPlayer != null) {
                mPlayer.getCostomMediaController().updatePausePlay();
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(@NonNull MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = event.getY();
                Log.e(TAG, "ACTION_DOWN:" + "startY:" + startY);
                break;
            case MotionEvent.ACTION_MOVE:
                if (nestedScrollY != 0) {
                    video_lockablenestedscrollview.getParent().requestDisallowInterceptTouchEvent(true);
                } else {
                    video_lockablenestedscrollview.getParent().requestDisallowInterceptTouchEvent(false);

                    if (event.getY() - startY > 0 && (Math.abs(event.getY() - startY) > startScrollY)) {
                        // 向下滑动
                        isStartDrag = true;
                    }
                    if (isStartDrag) {
                        moveY = event.getY() - startY;
                        isActionMove = true;
                        root_video.scrollBy(0, -(int) moveY);
                        startY = event.getY();
                        if (root_video.getScrollY() > 0) {
                            root_video.scrollTo(0, 0);
                        }
                        if (-root_video.getScrollY() > 0) {
                            video_lockablenestedscrollview.setScrollingEnabled(false);
                        } else {
                            video_lockablenestedscrollview.setScrollingEnabled(true);
                        }
                    }

                }
                Log.e(TAG, "ACTION_MOVE:" + "startY:" + startY + "---moveY:" + moveY + "---ScrollY:" + root_video.getScrollY());
                break;
            case MotionEvent.ACTION_UP:
                video_lockablenestedscrollview.setEnabled(true);
                if (root_video.getScrollY() < -Resources.getSystem().getDisplayMetrics().heightPixels / 4) {
                    finish();
                }
                isStartDrag = false;
                Log.e(TAG, "ACTION_UP:" + "startY:" + startY + "---moveY:" + moveY + "---ScrollY:" + root_video.getScrollY());
                if (isActionMove) {
                    isActionMove = false;
                    startTranslateAnimation(-root_video.getScrollY());
                    root_video.scrollTo(0, 0);
                }
                break;

        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    /**
     * 滑动动画
     *
     * @param y
     */
    public void startTranslateAnimation(float y) {
        TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, y, 0);
        //设置动画持续时长
        translateAnimation.setDuration(500);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        translateAnimation.setFillAfter(true);
        //开始动画
        root_video.startAnimation(translateAnimation);
    }

    public class VideoAdapter extends FragmentPagerAdapter {
        List<Fragment> fragmentList = new ArrayList();

        public VideoAdapter(@NonNull FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return (position == 0 ? "歌曲" : "简介");
        }
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


}
